package com.mililoan.persist.system.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.mililoan.common.bean.PageResultSet;
import com.mililoan.common.dao.AbstractBaseDao;
import com.mililoan.common.dao.JdbcPageResultSetDao;
import com.mililoan.common.utils.StackTraceUtil;
import com.mililoan.model.system.Actor;
import com.mililoan.persist.system.ActorDao;

/**
 * 功能表操作接口类
 * 
 * @author mwei
 *
 */
@Repository("ActorDao")
public class ActorDaoImpl extends AbstractBaseDao<Actor> implements ActorDao {	
	private static final Logger LOGGER = LoggerFactory.getLogger(ActorDaoImpl.class);
	private static final String SELECT_SQL = "SELECT T.ID,T.ACTOR_NAME,T.SUMMARY,T.DEP_CODE,T.ISVALID FROM SYS_ACTOR T ";
	
	/**
	 * 添加角色
	 * @param actor 角色
	 * @return
	 */
	public Integer addActor(final Actor actor){
		JdbcTemplate template = this.getJdbcTemplate();
		Integer newId = new Integer(0);
		final String sql = "INSERT INTO SYS_ACTOR(ACTOR_NAME,SUMMARY,DEP_CODE,ISVALID" 					
			+ ") VALUES (?,?,?,?)";
		// 取得新的ID
//		Integer newId = this.getSeqNextVal("SEQ_ACTOR_ID");
//		actor.setId(newId);
		try {
			//返回主键
			KeyHolder keyHolder = new GeneratedKeyHolder();
			template.update(new  PreparedStatementCreator(){
				public PreparedStatement createPreparedStatement(Connection con) throws SQLException {					
					PreparedStatement ps = con.prepareStatement(sql, 
								PreparedStatement.RETURN_GENERATED_KEYS);
							ps.setString(1, actor.getActorName());
							ps.setString(2, actor.getSummary());
							ps.setInt(3, actor.getDepCode());
							ps.setString(4, actor.getIsvalid());
					return ps;
				}
			},keyHolder);
			//获取主键
			newId = keyHolder.getKey().intValue();
		} catch (Exception e) {			
			LOGGER.error("--------新建角色时时出错------------");
			LOGGER.error(StackTraceUtil.getStackTrace(e));
		}
		return newId;	
	}
	
	public Integer updateActor(final Actor actor){
		JdbcTemplate template = this.getJdbcTemplate();
		String sql = " UPDATE SYS_ACTOR T SET T.ACTOR_NAME=?,T.SUMMARY=? "
				+ " WHERE T.ID=?";
		try {
			template.update(sql, new PreparedStatementSetter() {			
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(1, actor.getActorName());
					ps.setString(2, actor.getSummary());
					ps.setInt(3, actor.getId());
				}
			});
		} catch (DataAccessException e) {
			e.printStackTrace();
			LOGGER.error(StackTraceUtil.getStackTrace(e));
			return null;
		}
		return actor.getId();
	}

	/**
	 * 通过ID获得角色
	 * 
	 * @param id
	 *            角色ID
	 * @return
	 */
	public Actor getActorById(Integer id) {
//		String sql = "SELECT T.*,D.DEP_NAME FROM SYS_ACTOR T LEFT JOIN T_DEPARTMENT D ON T.DEP_CODE=D.DEP_CODE WHERE T.ACTOR_ID=?";
		final Actor actor = new Actor();
		JdbcTemplate template = this.getJdbcTemplate();
		String sql = SELECT_SQL + " WHERE T.ID = ?";
		
		try {
			template.query(sql, new Object[] { id }, new RowCallbackHandler() {
				public void processRow(ResultSet rs) throws SQLException {					
					actor.setId(rs.getInt("ID"));
					actor.setActorName(rs.getString("ACTOR_NAME"));
					actor.setSummary(rs.getString("SUMMARY"));
					actor.setDepCode(rs.getInt("DEP_CODE"));
					actor.setIsvalid(rs.getString("ISVALID"));
				}
			});
		} catch (Exception e) {
			LOGGER.error("通过ID获得角色时出错：", StackTraceUtil.getStackTrace(e));
			LOGGER.error(StackTraceUtil.getStackTrace(e));
		}
		return actor.getId() != null ? actor : null;
	}

	/**
	 * 查询角色
	 * 
	 * @param actor
	 *            角色
	 * @return
	 */
	public PageResultSet<Actor> queryActor(Actor actor, int page, int pageSize) {
		// 查询需要的参数
		ArrayList<Object> rag = new ArrayList<Object>();
		StringBuffer sql = new StringBuffer(
				SELECT_SQL + " WHERE 1=1");
		if (null != actor.getDepCode()) {
			sql.append(" AND T.DEP_CODE=? ");
			rag.add(actor.getDepCode());
		}
		if (StringUtils.isNotEmpty(actor.getDepName())) {
			sql.append(" AND D.DEP_NAME=? ");
			rag.add(actor.getDepName());
		}
		if (StringUtils.isNotEmpty(actor.getActorName())) {
			sql.append(" AND T.ACTOR_NAME LIKE ? ");
			rag.add("%" + actor.getActorName() + "%");
		}

		JdbcTemplate template = this.getJdbcTemplate();
		final JdbcPageResultSetDao<Actor> pageDao = new JdbcPageResultSetDao<Actor>(pageSize);
		pageDao.setPage(page);

		@SuppressWarnings("unchecked")
		final List<Actor> pageList = pageDao.getPrs().getResult();
		PageResultSet<Actor> l_pageResultSet = null;

		try {
			l_pageResultSet = pageDao.pageResultSet(sql.toString(), template, rag.toArray(), new RowCallbackHandler() {
				public void processRow(ResultSet rs) throws SQLException {
					Actor actor = buildActor(rs);
					pageList.add(actor);
				}
			});
		} catch (Exception e) {
			LOGGER.error("分页查询角色时出错：", StackTraceUtil.getStackTrace(e));
			return null;
		}
		return l_pageResultSet;
	}

	/**
	 * 获取本部门可使用的角色
	 * 
	 * @param depCode
	 *            部门code
	 * @return 角色列表
	 * @author mwei
	 */
//	public ArrayList<Actor> getDepartmentActor(final Integer depCode) {
//		final ArrayList<Actor> actors = new ArrayList<Actor>();
//		// name 暂存表
//		final ArrayList<String> actorNames = new ArrayList<String>();
//		String suppers = this.getSupperCodes(depCode);
//		JdbcTemplate template = this.getJdbcTemplate();
//		String sql;
//		sql = "SELECT * FROM SYS_ACTOR T WHERE T.DEP_CODE IN (" + suppers
//				+ ") ORDER BY T.DEP_CODE DESC,T.SCOPE DESC,T.DEFAULT_FLAG DESC";
//		try {
//			template.query(sql, new RowCallbackHandler() {
//				public void processRow(ResultSet rs) throws SQLException {
//					String theScope = rs.getString("SCOPE");
//					Integer theDepDode = rs.getInt("DEP_CODE");
//					String theName = rs.getString("ACTOR_NAME");
//					// 不是共享权限 且 不是当前部门的
//					if ("1".equalsIgnoreCase(theScope) || theDepDode.intValue() == depCode.intValue()) {
//						if (!actorNames.contains(theName)) {
//							Actor actor = new Actor();
//							actor.setId(rs.getInt("ACTOR_ID"));
//							actor.setName(theName);
//							actor.setDefaultFlag(rs.getString("DEFAULT_FLAG"));
//							actor.setScope(theScope);
//							actor.setDepCode(theDepDode);
//							actors.add(actor);
//							actorNames.add(theName);
//						}
//					}
//				}
//			});
//		} catch (Exception e) {
//			e.printStackTrace();
//			System.out.println("--------获取可用角色时出错------------");
//			System.out.println(e.getMessage());
//			return null;
//		}
//		return actors;
//	}

	/**
	 * 获取本部门默认角色
	 * 
	 * @param depCode
	 *            部门code
	 * @return 角色
	 * @author mwei
	 */
//	public Actor getDefaultDepartmentActo(final Integer depCode) {
//		final Actor actor = new Actor();
//		String suppers = this.getSupperCodes(depCode);
//		JdbcTemplate template = this.getJdbcTemplate();
//		String sql;
//		sql = "SELECT T.* FROM T_DEPARTMENT T WHERE (T.SHARE_ACTOR>=0 OR T.PRIVATE_ACTOR>=0) AND T.DEP_CODE IN("
//				+ suppers + ") ORDER BY T.DEP_CODE";
//		try {
//			template.query(sql, new RowCallbackHandler() {
//				public void processRow(ResultSet rs) throws SQLException {
//					Integer shareActor = rs.getInt("SHARE_ACTOR");
//					if (null != shareActor) {
//						actor.setId(shareActor);
//					}
//					Integer privateActor = rs.getInt("PRIVATE_ACTOR");
//					if (null != privateActor && (0 != privateActor) && depCode == rs.getInt("DEP_CODE")) {
//						actor.setId(privateActor);
//					}
//				}
//			});
//		} catch (Exception e) {
//			e.printStackTrace();
//			System.out.println("--------获取默认角色时出错------------");
//			System.out.println(e.getMessage());
//			return null;
//		}
//		return actor;
//	}

	/**
	 * 获取默认角色名
	 * 

	 * @return 角色
	 * @author mwei
	 */
	public String getDefaultActoName() {
		final Actor actor = new Actor();
		JdbcTemplate template = this.getJdbcTemplate();
		String sql;
		sql = "SELECT T.* FROM SYS_ACTOR T WHERE  AND T.DEP_CODE=0";
		try {
			template.query(sql, new RowCallbackHandler() {
				public void processRow(ResultSet rs) throws SQLException {
					actor.setActorName(rs.getString("ACTOR_NAME"));
				}
			});
		} catch (Exception e) {
			LOGGER.error("--------获取默认角色时出错------------");
			LOGGER.error("获取默认角色名：", StackTraceUtil.getStackTrace(e));
			return null;
		}
		return actor.getActorName();
	}

	/**
	 * 根据部门code获取所有上级部门code
	 * 
	 * @param code
	 *            部门IDcode
	 * @return 所有code ,号隔开
	 */
//	public String getSupperCodes(Integer code) {
//		StringBuffer codes = new StringBuffer(code.toString());
//		while (code > 0) {
//			code = code / 100;
//			codes.append("," + code.toString());
//		}
//		return codes.toString();
//	}

	public ArrayList<Actor> getAllActors(){
		final ArrayList<Actor> actors = new ArrayList<Actor>();
		JdbcTemplate template = this.getJdbcTemplate();
		String sql;
		sql = "SELECT * FROM SYS_ACTOR T ORDER BY T.DEP_CODE DESC,T.SCOPE DESC,T.DEFAULT_FLAG DESC";
		try {
			template.query(SELECT_SQL, new RowCallbackHandler() {
				public void processRow(ResultSet rs) throws SQLException {
					Actor actor = buildActor(rs);
					actors.add(actor);
				}
			});
		} catch (Exception e) {
			LOGGER.error("--------获取可用角色时出错------------");
			LOGGER.error("获取默认角色名：", StackTraceUtil.getStackTrace(e));
			return null;
		}
		return actors;
	}
	
	private Actor buildActor(ResultSet rs) {
	 	Actor rsActor = new Actor();
	 	try {
			rsActor.setId(rs.getInt("ID"));
			rsActor.setActorName(rs.getString("ACTOR_NAME"));
			rsActor.setSummary(rs.getString("SUMMARY"));
			rsActor.setDepCode(rs.getInt("DEP_CODE"));
			rsActor.setIsvalid(rs.getString("ISVALID"));
		} catch (Exception e) {
            LOGGER.error(StackTraceUtil.getStackTrace(e));
        }
		return rsActor;
	 }
}
